<?php

class JoinCollection {

    /**
     * @var Join[]
     */
    private $joins;

    /**
     * @param string $sourceTableName
     * @param string $targetTableName
     * @param Criteria $criteria
     * @param string $type
     */
    public function createAndAddJoin($sourceTableName, $targetTableName, $criteria = null, $type = '') {
        $this->joins[] = new Join($sourceTableName, $targetTableName, $criteria, $type);
    }

    /**
     * @param Join $join
     */
    public function addJoin($join) {
        $this->joins[] = $join;
    }

    /**
     * @return string
     */
    public function getJoinCollectionString() {
        if(count($this->joins) == 0) { return ''; }
        $joinCollectionString = '';
        foreach($this->joins as $join) {
            $joinCollectionString .= $join->getJoinString() . ' ';
        }
        $joinCollectionString = substr($joinCollectionString, 0, strlen($joinCollectionString)-1);
        return $joinCollectionString ? $joinCollectionString : '';
    }

    /**
     * @return int
     */
    public function getJoinCount() {
        return count($this->joins);
    }

    /**
     * @param $sourceTableName
     * @return array
     */
    public function getJoinsBySourceTableName($sourceTableName) {
        $joins = array();
        foreach($this->joins as $join)
        {
            if($join->sourceTableName == $sourceTableName) {
                $joins[] = $join;
            }
        }
        return $joins;
    }

    /**
     * @param $targetTableName
     * @return array
     */
    public function getJoinsByTargetTableName($targetTableName) {
        $joins = array();
        foreach($this->joins as $join)
        {
            if($join->targetTableName == $targetTableName) {
                $joins[] = $join;
            }
        }
        return $joins;
    }

}